package server.tasks;

import java.sql.*;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

import server.MonitoringData;
import server.NodeInfo;

public class MonitorTask implements Callable<MonitorTask> {
	private NodeInfo node;
	private Long timeStarted;
	private static final String LOCKS_QUERY = 
		"select count(0) from pg_locks";
	
	public Future<MonitorTask> future;
	public MonitoringData result;
	
	public MonitorTask(NodeInfo node, Long timeStarted){
		this.node = node;
		this.timeStarted = timeStarted;
	}

	@Override
	public MonitorTask call() throws Exception {
		result = new MonitoringData();
		Long start = System.currentTimeMillis();
		Integer locksCount = null;
		Connection connection = null;
		
		try {
			connection = DriverManager.getConnection(node.getUrl(), node.getUser(), node.getPassword());
			Statement sqlStatement = connection.createStatement();					
			sqlStatement.execute(MonitorTask.LOCKS_QUERY);
			ResultSet queryResult = sqlStatement.getResultSet();	
			queryResult.next();
			locksCount = queryResult.getInt(1);
			connection.close();
		} catch (SQLException e) {
			if(connection != null)
				connection.close();
		}
		
		result.setLocksCount(locksCount);
		if(start != null)
			result.setResponseTime(System.currentTimeMillis() - start);		
		result.setTimeStamp(timeStarted);
		result.setConnection(node);
		return this;
	}

	public void setNode(NodeInfo info) {
		this.node = info;
	}

	public NodeInfo getNode() {
		return node;
	}
}
